package nio.多线程优化01;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * MultiThreadServer
 *
 * @author chenxin
 * @date 2022/05/25 18:27
 **/
public class MultiThreadServer {

    /**
     * 功能描述: 核心思想：使用多个Selector（线程）执行事件，其中一个selector用于管理连接事件(boss)，其他的用于管理读写事件(worker).
     *
     * @author: chenxin
     * @date: 2022/5/25
     */
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");

        // 创建boss selector
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        ssc.register(boss, SelectionKey.OP_ACCEPT, null);
        ssc.bind(new InetSocketAddress(8080));

        // 1. 创建固定数量的worker 并初始化
        Worker worker = new Worker("工作者01");
        while (true) {
            boss.select();

            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    System.out.println("connected.." + sc.getRemoteAddress());

                    // 2.关联worker
                    System.out.println("before.." + sc.getRemoteAddress());
                    worker.register(sc);
                    System.out.println("after.." + sc.getRemoteAddress());
                }

            }
        }
    }

    // worker类 处理读写
    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        // 标记是否初始化
        private volatile boolean initSign;

        public Worker(String name) {
            this.name = name;
        }

        // 初始化worker
        public void  register(SocketChannel sc) throws IOException {
            if (!initSign) {
                thread = new Thread(this, name);
                selector = Selector.open();
                initSign = true;
                thread.start();
            }

            sc.register(selector, SelectionKey.OP_READ, null);
        }

        @Override
        public void run() {
            // 监测读写事件
            while (true) {
                try {
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();

                        if (key.isReadable()) {
                            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            System.out.println("read..."+channel.getRemoteAddress());
                            channel.read(byteBuffer);
                            byteBuffer.flip();

                            System.out.println(Charset.defaultCharset().decode(byteBuffer));
                        }

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}